package com.example.userservice.controller;

import com.example.userservice.entity.user_account;
import com.example.userservice.service.UserRoleService;
import com.example.userservice.service.UserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class LoginAndRegisterController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    
    // 处理GET请求的登录页面
    // @GetMapping("/Login")
    // public String loginPage(String msg, Model model) {
    //     if (msg != null) {
    //         model.addAttribute("errorMessage", msg);
    //     }
    //     return "Login";
    // }
    @PostMapping("/Register")
    @Transactional
    public String Register(String username, String password, String email){
        boolean emailExists = userService.lambdaQuery()
                .eq(com.example.userservice.entity.user_account::getEmail, email)
                .count() > 0;
        if (emailExists) {
            String msg = URLEncoder.encode("该邮箱已被注册", StandardCharsets.UTF_8);
            return "redirect:/Login?msg=" + msg;
        }
        
        // 创建用户
        user_account user = new user_account();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setStatus(2);
        
        // 保存用户
        userService.save(user);
        
        // 为新用户分配默认角色
        com.example.userservice.entity.UserRole userRole = new com.example.userservice.entity.UserRole(user.getId(), 1);
        userRoleService.save(userRole);
        
        String msg = URLEncoder.encode("注册成功", StandardCharsets.UTF_8);
        return "redirect:/Login?msg=" + msg;
    }

    @RequestMapping("/login")
    public String LoginPage(){

        return "Login"; // return templates/Login.html
    }

    @PostMapping("/Login")
    public String Login(String email, String password, HttpSession session, HttpServletResponse response){
        // 根据邮箱查找用户
        user_account user = userService.lambdaQuery()
                .eq(com.example.userservice.entity.user_account::getEmail, email)
                .one();

        if (user == null || !password.equals(user.getPassword())) {
            // 用户名或密码错误
            String msg = URLEncoder.encode("账户名或密码错误", StandardCharsets.UTF_8);
            return "redirect:/Login?msg=" + msg;
        }
        
        // 获取用户角色
        int roleCode = userRoleService.lambdaQuery()
                .eq(com.example.userservice.entity.UserRole::getUserId, user.getId())
                .one()
                .getRoleId();
        
        // 将用户信息存储到Session中
        session.setAttribute("user", user);
        session.setAttribute("roleCode", roleCode);
        System.out.println("=== 登录调试信息 ===");
        System.out.println("用户ID: " + user.getId());
        System.out.println("用户邮箱: " + email);
        System.out.println("查询到的角色ID: " + roleCode);
        System.out.println("==================");

//         根据角色跳转到对应页面
//        switch (roleCode) {
//            case 1: // 学生
//                return "redirect:/HomeStu";
//            case 2: // 教师
//                return "redirect:/HomeTeacher";
//            case 3: // 管理员
//                return "redirect:/HomeAdmin";
//            default:
//                String msg = URLEncoder.encode("用户角色异常", StandardCharsets.UTF_8);
//                return "redirect:/Login?msg=" + msg;
//        }
        return "redirect:/login?roleCode=" + roleCode;
    }

    @RequestMapping("/HomeStu")
    public String HomeStu(HttpSession session, Model model){
        user_account user = (user_account) session.getAttribute("user");
        Integer roleCode = (Integer) session.getAttribute("roleCode");
        System.out.println("=== 访问学生页面 ===");
        System.out.println("用户: " + (user != null ? user.getUsername() : "null"));
        System.out.println("角色: " + roleCode);
        System.out.println("==================");
        
        if (user == null) {
            return "redirect:/Login";
        }
        model.addAttribute("user", user);
        return "HomeStu";
    }
    
    @RequestMapping("/HomeTeacher")
    public String HomeTeacher(HttpSession session, Model model){
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "redirect:/Login";
        }
        model.addAttribute("user", user);
        return "HomeTeacher";
    }
    
    @RequestMapping("/HomeAdmin")
    public String HomeAdmin(HttpSession session, Model model){
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "redirect:/Login";
        }
        model.addAttribute("user", user);
        return "HomeAdmin";
    }
    
    // 退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session, HttpServletResponse response) {
        // 清除Session
        session.invalidate();   
        return "redirect:/login";
    }
}
